import { defineStore } from 'pinia'
import type { User } from '@/common/types/user'

export const useUserStore = defineStore('user', () => {
  /** 用户信息 */
  const hope_user_info = ref<Optional<User> | null>()

  /** token */
  const hope_token = ref<string | null>()

  /** 设置用户信息 */
  const setUserInfo = (val: Optional<User>) => {
    hope_user_info.value = { ...hope_user_info.value, ...val }
  }

  /**
   * 设置token
   */
  const setToken = (token: string) => {
    hope_token.value = token
  }

  /** 清空用户信息 */
  const clearUserInfo = () => {
    hope_user_info.value = null
    hope_token.value = null
  }

  return {
    hope_user_info,
    hope_token,
    setToken,
    setUserInfo,
    clearUserInfo,
  }
}, {
  // 持久化存储用户信息
  persist: {
    // 调整为兼容多端的api 使用uniapp的api
    storage: {
      setItem(key, value) {
        uni.setStorageSync(key, value)
      },

      getItem(key) {
        return uni.getStorageSync(key)
      },
    },
  },
})
